import { login, logout } from "@/api/user";
import { getToken, setToken, removeToken, removeIsHome } from "@/utils/auth";
import router, { resetRouter } from "@/router";
const getDefaultState = () => {
  return {
    token: getToken(),
    user: null,
    name: null,
    shopUuid: null
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_USER: (state, user) => {
    state.user = user;
  },
  SET_SHOP_UUID: (state, shopUuid) => {
    state.shopUuid = shopUuid;
  },
  SET_LOGOUT: state => {
    state.user = null;
    state.name = null;
    state.shopUuid = null;
  }
};

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          if (response.items.shopUuid) {
            commit("SET_SHOP_UUID", response.items.shopUuid);
          }
          const user = { ...response.items };
          commit("SET_NAME", response.items.username);
          commit("SET_USER", user);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          removeIsHome();
          commit("RESET_STATE");
          commit("SET_LOGOUT");
          commit("menu/LOGOUT", [], { root: true });
          router.push("login");
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      removeToken();
      resolve();
    });
  },

  //刷新token--------------------------------------------
  reflashToken({ commit }, token) {
    commit("SET_TOKEN", token);
    setToken(token);
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response;

          if (!data) {
            return reject("Verification failed, please Login again.");
          }

          const { name, avatar } = data;

          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
